import axios from 'axios'

const instance = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          console.error('未授权，请登录')
          break
        case 403:
          console.error('拒绝访问')
          break
        case 404:
          console.error('请求资源未找到')
          break
        case 500:
          console.error('服务器内部错误')
          break
        default:
          console.error('请求失败', error.response.status)
      }
    } else if (error.request) {
      console.error('请求未响应', error.request)
    } else {
      console.error('请求设置错误', error.message)
    }
    return Promise.reject(error)
  },
)

const request = async (method, url, data = null, params = null) => {
  const response = await instance({
    method,
    url,
    data,
    params,
  })
  return response
}

export default {
  get: (url, params) => request('GET', url, null, params),
  post: (url, data) => request('POST', url, data),
  put: (url, data) => request('PUT', url, data),
  delete: (url, params) => request('DELETE', url, null, params),
}
